<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico">
  <link rel="mask-icon" href="/images/favicon.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css" integrity="sha256-mUZM63G8m73Mcidfrv5E+Y61y7a12O5mW4ezU3bxqW4=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"example.com","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.8.0","exturl":false,"sidebar":{"position":"left","display":"remove","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":"false;","trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>
<meta name="description" content="1.递归的概念递归就是方法自己调用自己,每次调用时传入不同的变量.递归有助于解决复杂的问题的同时还可以让代码变得更加简洁。但是值得注意的是，递归只是让解决方案变得清晰，并没有性能上的优势，有时甚至还没有循环的性能好，而这也是递归的主要缺点之一。 比如定义函数 f(x)&#x3D;x+f(x-1)：">
<meta property="og:type" content="article">
<meta property="og:title" content="递归算法学习笔记">
<meta property="og:url" content="http://example.com/2021/09/04/%E9%80%92%E5%BD%92%E7%AE%97%E6%B3%95%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/index.html">
<meta property="og:site_name" content="ADGai&#39;s Blog">
<meta property="og:description" content="1.递归的概念递归就是方法自己调用自己,每次调用时传入不同的变量.递归有助于解决复杂的问题的同时还可以让代码变得更加简洁。但是值得注意的是，递归只是让解决方案变得清晰，并没有性能上的优势，有时甚至还没有循环的性能好，而这也是递归的主要缺点之一。 比如定义函数 f(x)&#x3D;x+f(x-1)：">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/AD-Gai-Code/pic-go/raw/master/10.png">
<meta property="og:image" content="https://gitee.com/AD-Gai-Code/pic-go/raw/master/11.png">
<meta property="article:published_time" content="2021-09-04T14:32:51.527Z">
<meta property="article:modified_time" content="2021-10-26T09:22:24.397Z">
<meta property="article:author" content="AiLaodu">
<meta property="article:tag" content="数据结构与算法">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/AD-Gai-Code/pic-go/raw/master/10.png">


<link rel="canonical" href="http://example.com/2021/09/04/%E9%80%92%E5%BD%92%E7%AE%97%E6%B3%95%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://example.com/2021/09/04/%E9%80%92%E5%BD%92%E7%AE%97%E6%B3%95%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/","path":"2021/09/04/递归算法学习笔记/","title":"递归算法学习笔记"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>递归算法学习笔记 | ADGai's Blog</title>
  




  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">ADGai's Blog</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li>
        <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container"></div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container">
  <div class="algolia-stats"><hr></div>
  <div class="algolia-hits"></div>
  <div class="algolia-pagination"></div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/09/04/%E9%80%92%E5%BD%92%E7%AE%97%E6%B3%95%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="AiLaodu">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="ADGai's Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          递归算法学习笔记
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-09-04 22:32:51" itemprop="dateCreated datePublished" datetime="2021-09-04T22:32:51+08:00">2021-09-04</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-10-26 17:22:24" itemprop="dateModified" datetime="2021-10-26T17:22:24+08:00">2021-10-26</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/" itemprop="url" rel="index"><span itemprop="name">数据结构与算法</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="1-递归的概念"><a href="#1-递归的概念" class="headerlink" title="1.递归的概念"></a>1.递归的概念</h1><p>递归就是方法自己调用自己,每次调用时传入不同的变量.递归有助于解决复杂的问题的同时还可以让代码变得更加简洁。但是值得注意的是，递归只是让解决方案变得清晰，并没有性能上的优势，有时甚至还没有循环的性能好，而这也是递归的主要缺点之一。</p>
<p>比如定义函数 f(x)=x+f(x-1)：</p>
<span id="more"></span>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">f</span><span class="params">(<span class="keyword">int</span> x)</span></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> x + f(x-<span class="number">1</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="1-1-递归的条件和规则"><a href="#1-1-递归的条件和规则" class="headerlink" title="1.1 递归的条件和规则"></a>1.1 递归的条件和规则</h2><p>递归自己调用自己，因此写递归时很容易出错，陷入无限循环。因此编写递归方法时，必须设定条件告诉递归何时停止。如上面的例子：</p>
<p>如果代入 f(2)：</p>
<p>返回 2+f(1)；<br>       调用 f(1)；<br>       返回 1+f(0)；<br>       调用 f(0)；<br>       返回 0+f(-1)；<br>       ……</p>
<p>这时程序会无休止地运行下去，直到崩溃。</p>
<p>如果我们加一个判断语句 <strong>x&gt;0</strong>;</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">f</span><span class="params">(<span class="keyword">int</span> x)</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(x &gt; <span class="number">0</span>)&#123;</span><br><span class="line">    <span class="keyword">return</span> x + f(x-<span class="number">1</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这次计算 f(2)=2+f(1)=2+1+f(0)=2+1+0=3。</p>
<p>由此可得递归的两个规律：</p>
<ul>
<li>递归函数必须要有<strong>终止条件</strong>，否则会出错；</li>
<li>递归函数先不断调用自身，直到遇到终止条件后进行回溯，最终返回答案。</li>
</ul>
<blockquote>
<ol>
<li><p>执行一个方法时，就创建一个新的受保护的独立空间(栈空间)</p>
</li>
<li><p>方法的局部变量是独立的，不会相互影响, 比如 n 变量</p>
</li>
<li><p>如果方法中使用的是引用类型变量(比如数组)，就会共享该引用类型的数据.</p>
</li>
<li><p>递归必须向退出递归的条件逼近，否则就是无限递归,会报栈溢出的错误 。</p>
</li>
<li><p>当一个方法执行完毕，或者遇到 return，就会返回，遵守谁调用，就将结果返回给谁，同时当方法执行完毕或 者返回时，该方法也就执行完毕。   </p>
</li>
</ol>
</blockquote>
<h2 id="1-2-递归的机制图解"><a href="#1-2-递归的机制图解" class="headerlink" title="1.2 递归的机制图解"></a>1.2 递归的机制图解</h2><p><img src="https://gitee.com/AD-Gai-Code/pic-go/raw/master/10.png"></p>
<h1 id="2-递归的应用场景"><a href="#2-递归的应用场景" class="headerlink" title="2 递归的应用场景"></a>2 递归的应用场景</h1><h2 id="2-1-阶乘问题"><a href="#2-1-阶乘问题" class="headerlink" title="2.1 阶乘问题"></a>2.1 阶乘问题</h2><p>问题描述：使用递归方法来完成自然数的阶乘。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">factorial</span><span class="params">(<span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">   <span class="keyword">if</span> (n == <span class="number">1</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">     &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">       <span class="keyword">return</span> factorial(n - <span class="number">1</span>) * n; <span class="comment">// 1 * 2 * 3</span></span><br><span class="line">     &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="2-2-迷宫问题"><a href="#2-2-迷宫问题" class="headerlink" title="2.2 迷宫问题"></a>2.2 迷宫问题</h2><p><img src="https://gitee.com/AD-Gai-Code/pic-go/raw/master/11.png"></p>
<p>如图所示的迷宫为小球找到路，使其能走到迷宫的右下角。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.atguigu.recursion;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MiGong</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 先创建一个二维数组，模拟迷宫</span></span><br><span class="line">        <span class="comment">// 地图</span></span><br><span class="line">        <span class="keyword">int</span>[][] map = <span class="keyword">new</span> <span class="keyword">int</span>[<span class="number">8</span>][<span class="number">7</span>];</span><br><span class="line">        <span class="comment">// 使用1 表示墙</span></span><br><span class="line">        <span class="comment">// 上下全部置为1</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">7</span>; i++) &#123;</span><br><span class="line">            map[<span class="number">0</span>][i] = <span class="number">1</span>;</span><br><span class="line">            map[<span class="number">7</span>][i] = <span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 左右全部置为1</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">8</span>; i++) &#123;</span><br><span class="line">            map[i][<span class="number">0</span>] = <span class="number">1</span>;</span><br><span class="line">            map[i][<span class="number">6</span>] = <span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//设置挡板, 1 表示</span></span><br><span class="line">        map[<span class="number">3</span>][<span class="number">1</span>] = <span class="number">1</span>;</span><br><span class="line">        map[<span class="number">3</span>][<span class="number">2</span>] = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 输出地图</span></span><br><span class="line">        System.out.println(<span class="string">&quot;地图的情况&quot;</span>);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">8</span>; i++) &#123;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; <span class="number">7</span>; j++) &#123;</span><br><span class="line">                System.out.print(map[i][j] + <span class="string">&quot; &quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//使用递归回溯给小球找路</span></span><br><span class="line">        System.out.println(<span class="string">&quot;小球走过，并标识过的 地图的情况&quot;</span>);</span><br><span class="line">        setWay(map, <span class="number">1</span>, <span class="number">1</span>);</span><br><span class="line">        <span class="comment">//setWay2(map, 1, 1);</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//输出新的地图, 小球走过，并标识过的递归</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">8</span>; i++) &#123;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; <span class="number">7</span>; j++) &#123;</span><br><span class="line">                System.out.print(map[i][j] + <span class="string">&quot; &quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//使用递归回溯来给小球找路</span></span><br><span class="line">    <span class="comment">//说明</span></span><br><span class="line">    <span class="comment">//1. map 表示地图</span></span><br><span class="line">    <span class="comment">//2. i,j 表示从地图的哪个位置开始出发 (1,1)</span></span><br><span class="line">    <span class="comment">//3. 如果小球能到 map[6][5] 位置，则说明通路找到.</span></span><br><span class="line">    <span class="comment">//4. 约定： 当map[i][j] 为 0 表示该点没有走过 当为 1 表示墙  ； 2 表示通路可以走 ； 3 表示该点已经走过，但是走不通</span></span><br><span class="line">    <span class="comment">//5. 在走迷宫时，需要确定一个策略(方法) 下-&gt;右-&gt;上-&gt;左 , 如果该点走不通，再回溯</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> map 表示地图</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> i   从哪个位置开始找</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> j</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 如果找到通路，就返回true, 否则返回false</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">setWay</span><span class="params">(<span class="keyword">int</span>[][] map, <span class="keyword">int</span> i, <span class="keyword">int</span> j)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (map[<span class="number">6</span>][<span class="number">5</span>] == <span class="number">2</span>) &#123; <span class="comment">// 通路已经找到ok</span></span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            System.out.printf(<span class="string">&quot;(%d,%d)&quot;</span>, i, j);</span><br><span class="line">            System.out.println();</span><br><span class="line">            <span class="keyword">if</span> (map[i][j] == <span class="number">0</span>) &#123; <span class="comment">//如果当前这个点还没有走过</span></span><br><span class="line">                <span class="comment">//按照策略 下-&gt;右-&gt;上-&gt;左  走</span></span><br><span class="line">                map[i][j] = <span class="number">2</span>; <span class="comment">// 假定该点是可以走通.</span></span><br><span class="line">                <span class="keyword">if</span> (setWay(map, i + <span class="number">1</span>, j)) &#123;<span class="comment">//向下走</span></span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">                &#125; <span class="keyword">else</span> <span class="keyword">if</span> (setWay(map, i, j + <span class="number">1</span>)) &#123; <span class="comment">//向右走</span></span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">                &#125; <span class="keyword">else</span> <span class="keyword">if</span> (setWay(map, i - <span class="number">1</span>, j)) &#123; <span class="comment">//向上</span></span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">                &#125; <span class="keyword">else</span> <span class="keyword">if</span> (setWay(map, i, j - <span class="number">1</span>)) &#123; <span class="comment">// 向左走</span></span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    <span class="comment">//说明该点是走不通，是死路</span></span><br><span class="line">                    map[i][j] = <span class="number">3</span>;</span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123; <span class="comment">// 如果map[i][j] != 0 , 可能是 1， 2， 3</span></span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="2-3-N皇后问题"><a href="#2-3-N皇后问题" class="headerlink" title="2.3 N皇后问题"></a>2.3 N皇后问题</h2><p>问题描述（此处以8皇后为例）：在 8×8 格的国际象棋上摆放八个皇后，使其不能互相攻击，即：任意两个皇后都不能处于同一行、 同一列或同一斜线上，问有多少种摆法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.atguigu.recursion;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Queue8</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//定义一个max表示共有多少个皇后</span></span><br><span class="line">    <span class="keyword">int</span> max = <span class="number">8</span>;</span><br><span class="line">    <span class="comment">//定义数组array, 保存皇后放置位置的结果,比如 arr = &#123;0 , 4, 7, 5, 2, 6, 1, 3&#125; </span></span><br><span class="line">    <span class="keyword">int</span>[] array = <span class="keyword">new</span> <span class="keyword">int</span>[max];</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">int</span> count = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">int</span> judgeCount = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//测试一把 ， 8皇后是否正确</span></span><br><span class="line">        Queue8 queue8 = <span class="keyword">new</span> Queue8();</span><br><span class="line">        queue8.check(<span class="number">0</span>);</span><br><span class="line">        System.out.printf(<span class="string">&quot;一共有%d解法&quot;</span>, count);</span><br><span class="line">        System.out.printf(<span class="string">&quot;一共判断冲突的次数%d次&quot;</span>, judgeCount); <span class="comment">// 1.5w</span></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">//编写一个方法，放置第n个皇后</span></span><br><span class="line">    <span class="comment">//特别注意： check 是 每一次递归时，进入到check中都有  for(int i = 0; i &lt; max; i++)，因此会有回溯</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">check</span><span class="params">(<span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (n == max) &#123;  <span class="comment">//n = 8 , 其实8个皇后就已然放好</span></span><br><span class="line">            print();</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//依次放入皇后，并判断是否冲突</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; max; i++) &#123;</span><br><span class="line">            <span class="comment">//先把当前这个皇后 n , 放到该行的第1列</span></span><br><span class="line">            array[n] = i;</span><br><span class="line">            <span class="comment">//判断当放置第n个皇后到i列时，是否冲突</span></span><br><span class="line">            <span class="keyword">if</span> (judge(n)) &#123; <span class="comment">// 不冲突</span></span><br><span class="line">                <span class="comment">//接着放n+1个皇后,即开始递归</span></span><br><span class="line">                check(n + <span class="number">1</span>); <span class="comment">//  </span></span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">//如果冲突，就继续执行 array[n] = i; 即将第n个皇后，放置在本行得 后移的一个位置</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//查看当我们放置第n个皇后, 就去检测该皇后是否和前面已经摆放的皇后冲突</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> n 表示第n个皇后</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">judge</span><span class="params">(<span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">        judgeCount++;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">            <span class="comment">// 说明</span></span><br><span class="line">            <span class="comment">//1. array[i] == array[n]  表示判断 第n个皇后是否和前面的n-1个皇后在同一列</span></span><br><span class="line">            <span class="comment">//2. Math.abs(n-i) == Math.abs(array[n] - array[i]) 表示判断第n个皇后是否和第i皇后是否在同一斜线</span></span><br><span class="line">            <span class="comment">// n = 1  放置第 2列 1 n = 1 array[1] = 1</span></span><br><span class="line">            <span class="comment">// Math.abs(1-0) == 1  Math.abs(array[n] - array[i]) = Math.abs(1-0) = 1</span></span><br><span class="line">            <span class="comment">//3. 判断是否在同一行, 没有必要，n 每次都在递增</span></span><br><span class="line">            <span class="keyword">if</span> (array[i] == array[n] || Math.abs(n - i) == Math.abs(array[n] - array[i])) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//写一个方法，可以将皇后摆放的位置输出</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">print</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        count++;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; array.length; i++) &#123;</span><br><span class="line">            System.out.print(array[i] + <span class="string">&quot; &quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>说明： 理论上应该创建一个二维数组来表示棋盘，但是实际上可以通过算法，用一个一维数组即可解决问题. </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">arr[<span class="number">8</span>] = &#123;<span class="number">0</span> , <span class="number">4</span>, <span class="number">7</span>, <span class="number">5</span>, <span class="number">2</span>, <span class="number">6</span>, <span class="number">1</span>, <span class="number">3</span>&#125; <span class="comment">//对应 arr 下标 表示第几行，即第几个皇后，arr[i] = val , val 表示第 i+1 个皇后，放在第 i+1 行的第 val+1 列。</span></span><br></pre></td></tr></table></figure>

<h1 id="3-leetcode上对应的easy递归题目"><a href="#3-leetcode上对应的easy递归题目" class="headerlink" title="3 leetcode上对应的easy递归题目"></a>3 leetcode上对应的easy递归题目</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">206.</span>反转一个单链表。</span><br><span class="line"></span><br><span class="line">示例:</span><br><span class="line"></span><br><span class="line">输入: <span class="number">1</span>-&gt;<span class="number">2</span>-&gt;<span class="number">3</span>-&gt;<span class="number">4</span>-&gt;<span class="number">5</span>-&gt;NULL</span><br><span class="line">输出: <span class="number">5</span>-&gt;<span class="number">4</span>-&gt;<span class="number">3</span>-&gt;<span class="number">2</span>-&gt;<span class="number">1</span>-&gt;NULL</span><br><span class="line">进阶:</span><br><span class="line">你可以迭代或递归地反转链表。你能否用两种方法解决这道题？</span><br><span class="line"></span><br><span class="line">来源：力扣（LeetCode）</span><br><span class="line">链接：https:<span class="comment">//leetcode-cn.com/problems/reverse-linked-list</span></span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">递归解法</span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Solution</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> ListNode <span class="title">reverseList</span><span class="params">(ListNode head)</span> </span>&#123;</span><br><span class="line">		<span class="comment">//递归终止条件是当前为空，或者下一个节点为空</span></span><br><span class="line">		<span class="keyword">if</span>(head==<span class="keyword">null</span> || head.next==<span class="keyword">null</span>) &#123;</span><br><span class="line">			<span class="keyword">return</span> head;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">//这里的cur就是最后一个节点</span></span><br><span class="line">		ListNode cur = reverseList(head.next);</span><br><span class="line">		<span class="comment">//这里请配合动画演示理解</span></span><br><span class="line">		<span class="comment">//如果链表是 1-&gt;2-&gt;3-&gt;4-&gt;5，那么此时的cur就是5</span></span><br><span class="line">		<span class="comment">//而head是4，head的下一个是5，下下一个是空</span></span><br><span class="line">		<span class="comment">//所以head.next.next 就是5-&gt;4</span></span><br><span class="line">		head.next.next = head;</span><br><span class="line">		<span class="comment">//防止链表循环，需要将head.next设置为空</span></span><br><span class="line">		head.next = <span class="keyword">null</span>;</span><br><span class="line">		<span class="comment">//每层递归函数都返回cur，也就是最后一个节点</span></span><br><span class="line">		<span class="keyword">return</span> cur;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">509.</span>斐波那契数，通常用 F(n) 表示，形成的序列称为 斐波那契数列 。该数列由 <span class="number">0</span> 和 <span class="number">1</span> 开始，后面的每一项数字都是前面两项数字的和。也就是：</span><br><span class="line"></span><br><span class="line">F(<span class="number">0</span>) = <span class="number">0</span>，F(<span class="number">1</span>) = <span class="number">1</span></span><br><span class="line">F(n) = F(n - <span class="number">1</span>) + F(n - <span class="number">2</span>)，其中 n &gt; <span class="number">1</span></span><br><span class="line">给你 n ，请计算 F(n) 。</span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"></span><br><span class="line">示例 <span class="number">1</span>：</span><br><span class="line"></span><br><span class="line">输入：<span class="number">2</span></span><br><span class="line">输出：<span class="number">1</span></span><br><span class="line">解释：F(<span class="number">2</span>) = F(<span class="number">1</span>) + F(<span class="number">0</span>) = <span class="number">1</span> + <span class="number">0</span> = <span class="number">1</span></span><br><span class="line">示例 <span class="number">2</span>：</span><br><span class="line"></span><br><span class="line">输入：<span class="number">3</span></span><br><span class="line">输出：<span class="number">2</span></span><br><span class="line">解释：F(<span class="number">3</span>) = F(<span class="number">2</span>) + F(<span class="number">1</span>) = <span class="number">1</span> + <span class="number">1</span> = <span class="number">2</span></span><br><span class="line">示例 <span class="number">3</span>：</span><br><span class="line"></span><br><span class="line">输入：<span class="number">4</span></span><br><span class="line">输出：<span class="number">3</span></span><br><span class="line">解释：F(<span class="number">4</span>) = F(<span class="number">3</span>) + F(<span class="number">2</span>) = <span class="number">2</span> + <span class="number">1</span> = <span class="number">3</span></span><br><span class="line"></span><br><span class="line">来源：力扣（LeetCode）</span><br><span class="line">链接：https:<span class="comment">//leetcode-cn.com/problems/fibonacci-number</span></span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span> </span>&#123;    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">fib</span><span class="params">(<span class="keyword">int</span> n)</span> </span>&#123;        </span><br><span class="line">        <span class="keyword">int</span> Fn = <span class="number">0</span>;        </span><br><span class="line">        <span class="keyword">if</span>(n==<span class="number">0</span>)&#123;            </span><br><span class="line">            <span class="keyword">return</span> <span class="number">0</span>;        </span><br><span class="line">        &#125;        </span><br><span class="line">        <span class="keyword">if</span>(n==<span class="number">1</span>)&#123;            </span><br><span class="line">            <span class="keyword">return</span> <span class="number">1</span>;        </span><br><span class="line">        &#125;        </span><br><span class="line">        Fn = fib(n-<span class="number">1</span>)+fib(n-<span class="number">2</span>);        </span><br><span class="line">        <span class="keyword">return</span> Fn;    </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>需要注意的是，对这题来说递归并不是最好的解法，相较于动态优化来说其性能并不是很优。</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/" rel="tag"># 数据结构与算法</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/09/04/%E6%9E%9A%E4%B8%BE%E4%B8%8E%E6%B3%A8%E8%A7%A3%E5%A4%8D%E4%B9%A0%E6%80%BB%E7%BB%93/" rel="prev" title="枚举与注解复习总结">
                  <i class="fa fa-chevron-left"></i> 枚举与注解复习总结
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/11/02/TCP%E7%9A%84%E4%B8%89%E6%AC%A1%E6%8F%A1%E6%89%8B/" rel="next" title="TCP的三次握手">
                  TCP的三次握手 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">AiLaodu</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  
<script src="https://cdn.jsdelivr.net/npm/algoliasearch@4.10.5/dist/algoliasearch-lite.umd.js" integrity="sha256-HWlivbjXc58GuU4EIZziqIE83FFZ/da42de13pGZnMA=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/instantsearch.js@4.30.2/dist/instantsearch.production.min.js" integrity="sha256-eqhx/eer5fsD7YooSb21wsfJaQkJ/4gF3bmRBZP7q2o=" crossorigin="anonymous"></script><script src="/js/third-party/search/algolia-search.js"></script>





  





</body>
</html>
